<template>
  <div id="pie"></div>
</template>

<script>
  // 引入Echarts
  import * as echarts from 'echarts';
  export default {
    name: 'Pie',
    data() {
      return {
        charts: '',
        opinion:['直接访问','邮件营销','联盟广告','视频广告','搜索引擎'],
        opinionData:[
          {value:335, name:'直接访问'},
          {value:310, name:'邮件营销'},
          {value:234, name:'联盟广告'},
          {value:135, name:'视频广告'},
          {value:1548, name:'搜索引擎'}
        ]
      }
    },
    methods: {
      drawPie(id) {
        // 初始化图表
        this.charts = echarts.init(document.getElementById(id))
        this.charts.setOption({
          title: {
            text: '用户访问来源',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: 'Access From',
              type: 'pie',
              radius: '50%',
              data: this.opinionData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        })
      }
    },
    mounted() {
      this.drawPie('pie')
      //建议加上以下这一行代码，不加的效果图如下（当浏览器窗口缩小的时候）。超过了div的界限（红色边框）
      let that = this // 需要拿出 this 不然调用不到 charts
      window.addEventListener('resize', () => { that.charts.resize() });
    }
  }
</script>

<style scoped>
  #pie {
    width: 600px;
    height: 450px;
    background-color: #fff;
    border-radius: 5px;
    padding: 50px 30px;
    box-shadow: 2px 2px 5px #ddd;
    margin-right: 10px;
  }
</style>